using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using AppTableUtils;
using UnityEngine;
using DG.Tweening;
using Unity.VisualScripting;


/// <summary>
/// 古希腊掌管指定背包的神
/// </summary>
public class SelectedBagManager : MonoBehaviour
{
    public CreateImg bag_manager;
    public CreateImg store_manager;

    private int current_slot_index => bag_manager.current_slot_index;
    private DataTable bag_dt => bag_manager.bag_dt;

    public void btn_buy()
    {
        BdPackage.BdUtils.assert(store_manager != null, "store_manager不能为null!");
        
        var row_i = store_manager.get_bag_row_i(store_manager.current_slot_index);
        if (row_i == null)
        {
            return;
        }
        
        var item_info_row = store_manager.get_item_info_by_bag_row_i(row_i);
        int item_id = BdPackage.BdUtils.conv_to_int(item_info_row["ID"]);
        
        core_change_item_nums_in_bag_slot(slot_index: store_manager.current_slot_index, delta: -1, target_manager: store_manager);
        
        _btn_add_item(item_id: item_id, target_manager: bag_manager);
    }
    
    public void core_change_item_nums_in_bag_slot(int slot_index = -1, int delta = 1, int item_id = -1, CreateImg target_manager = null)
    {
        target_manager = target_manager == null ? bag_manager : target_manager;
        
        # region 这里处理`bag_dt`中没有的`item`的情况
        if (item_id != -1 && delta > 0)
        {
            BdUtils.assert(item_id > 0, "`slot_index`无对应行, 且`item_id`未赋值?");
        
            DataRow new_row = bag_dt.NewRow();
            new_row["物品ID"] = item_id;
            new_row["数量"] = delta;
            
            new_row["名称"] = TableUtils.get(target_manager.item_dt, item_id)["名称"];

            string target_column_name = "格子位置";

            int new_slot_index =
                TableUtils.get_available_index_for_selected_column(bag_dt, target_column_name, ignore_gap: false, min_index: -1);
            
            new_row["ID"] = TableUtils.get_available_index_for_selected_column(bag_dt, "ID", ignore_gap: true);
            new_row[target_column_name] = new_slot_index;
            
            BdPackage.BdUtils.log("new_row --- ", TableUtils.conv_row_to_dc(new_row));

            bag_dt.Rows.Add(new_row);

            BdPackage.BdUtils.assert(new_slot_index < target_manager.bag_capacity,
                $"new_slot_index[{new_slot_index}] 超出了 bag_capacity[{target_manager.bag_capacity}]?");
            
            BdPackage.BdUtils.log($"--- 从0开始增加`delta`[{delta}]的情况! item_id: {item_id}, new_slot_index: {new_slot_index}");

            target_manager.refresh_slot_grid();
            StartCoroutine(target_manager._save_bag_dt());
            
            show_add_animation(new_slot_index, target_manager);
            return;
        }
        # endregion 
        
        if (slot_index == -1 || delta == 0)
        {
            BdPackage.BdUtils.log($"--- 无效的slot_index[{slot_index}]? delta: {delta}");
            return;
        }
        
        # region 这里要处理已经在`bag_dt`中存在的`item`的情况
        var row_i = target_manager.get_bag_row_i(slot_index);
        if (row_i == null)
        {
            BdPackage.BdUtils.log($"--- 无效的row_i? --- slot_index[{slot_index}], delta: {delta}");
            return;
        }
        
        int remain_count = BdUtils.conv_to_int(row_i["数量"], 0);
        if (remain_count <= 0 && delta < 0)
        {
            BdPackage.BdUtils.log("--- 删除 1 --- row_i:", TableUtils.conv_row_to_dc(row_i));
            target_manager.bag_dt.Rows.Remove(row_i);
            StartCoroutine(target_manager._save_bag_dt());
            return;
        }
        var item_info_row = target_manager.get_item_info_by_bag_row_i(row_i);
        
        // string img_path = BdUtils.conv_to_string(item_info_row["图片"]);
        string item_name = BdUtils.conv_to_string(item_info_row["名称"]);

        BdPackage.BdUtils.log("--- 当前选中物品的信息, item_name:", item_name, ", remain_count:", remain_count, ", delta:", delta);

        remain_count += delta;
        if (remain_count <= 0)
        {
            // && target_manager.bag_dt.Rows.Contains(row_i)
            BdPackage.BdUtils.log("--- 删除 2 --- row_i:", TableUtils.conv_row_to_dc(row_i));
            target_manager.bag_dt.Rows.Remove(row_i);
        }
        row_i["数量"] = remain_count;

        target_manager.refresh_slot_grid();
        StartCoroutine(target_manager._save_bag_dt());
        
        show_add_animation(slot_index, target_manager);
        # endregion
    }

    void show_add_animation(int slot_index, CreateImg target_manager = null)
    {
        target_manager = target_manager == null ? bag_manager : target_manager;

        float t = 0.1f;  // [延迟/等待/休眠/timeout]t秒后执行
        DOTween.To(() => t, (x) => t = x, 0, t).OnComplete(
            () =>
            {
                string slot_path = BdUtils.join(BdTools.get_abs_path_by_obj(target_manager.transform.parent.gameObject), $"grid/slot_{slot_index}");
                GameObject slot_obj = GameObject.Find(slot_path);
                // BdPackage.BdUtils.log("--- slot_obj:", slot_obj.name, slot_obj == null, "---", slot_path);
                BdPackage.BdUtils.assert(slot_obj != null, $"slot_path[{slot_path}]对应的obj为空?");
                
                // 放大到两倍大小，然后再恢复到原始大小
                if (slot_obj.transform.localScale.x != 1.0f)
                    return;
                
                float max_scale = 1.5f;
                slot_obj.transform.DOScale(slot_obj.transform.localScale * max_scale,  0.5f) // 放大到两倍大小，耗时1秒
                    .SetEase(Ease.OutElastic) // 使用缓动效果，可以根据需求选择不同的缓动类型
                    .OnComplete(() =>
                    {
                        // 在动画完成时执行的操作，可以留空
                        // 这里可以添加恢复原始大小的Tween动画
                        if (slot_obj.IsDestroyed() || slot_obj.transform.IsDestroyed())
                            return;
                        slot_obj.transform.DOScale(slot_obj.transform.localScale / max_scale,  1f) // 恢复到原始大小，耗时1秒
                            .SetEase(Ease.InQuad); // 使用缓动效果
                    });
            }
            );
    }

    void _btn_add_one(int slot_index = -1, CreateImg target_manager = null)
    {
        core_change_item_nums_in_bag_slot(slot_index, delta: 1, target_manager: target_manager);
    }
    public void btn_add_one(int slot_index = -1)
    {
        _btn_add_one(slot_index);
    }

    void _btn_add_item(int item_id = -1, CreateImg target_manager = null)
    {
        
        target_manager = target_manager == null ? bag_manager : target_manager;

        if (item_id == -1)
            return;
        
        DataRow _item_info_row = null;
        var select = $"物品ID='{item_id}'";
        try
        {
            _item_info_row = AppTableUtils.TableUtils.get(target_manager.bag_dt, select: select);
        }
        catch (Exception e)
        {
            BdPackage.BdUtils.raise_exception_error_func($"error! select: [{select}]! error: {e}");
        }
        if (BdUtils.is_null(_item_info_row))
        {
            core_change_item_nums_in_bag_slot(item_id: item_id);
            return;
        }
        else
        {
        }
        BdPackage.BdUtils.log("--- item_info_row:", TableUtils.conv_row_to_dc(_item_info_row));
        int slot_index = BdUtils.conv_to_int(_item_info_row["格子位置"]);
        
        _btn_add_one(slot_index, target_manager);
    }
    
    public void btn_add_item(int item_id = -1)
    {
        _btn_add_item(item_id);
    }

    // Start is called before the first frame update
    void Start()
    {
        // var rows = bag_dt.Select("ID=1");
        // TableUtils.remove_rows(bag_dt, rows);
        
        // var row = TableUtils.get(bag_dt, pk: 1);
        // bag_dt.Rows.Remove(row);

        // TableUtils.swap_row(bag_dt, 1, 2);
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}
